package org.klaoye.musicplayer;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Service;
import android.bluetooth.BluetoothClass;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.klaoye.musicplayer.bean.FileSelector;
import org.klaoye.musicplayer.bean.MessageDriver;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ChannelFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener, ServiceConnection {
    public Handler handler;
    int position;
    File rootPath;//根目录
    File currentFile;//当前所在目录
    File[] files;//遍历得到的文件组
    File[] rootFiles;
    Button choseFileBtn, lastBtn;//（选择，上一个）按钮
    ListView fileListView;//显示目录的ListView
    ArrayList<String> fileNames;//文件名组
    FileSelector selector;//文件选择器
    Bundle bundle;//传数据
    MainActivity mainActivity;
    final String[] law = {".mp3", ".wav"};
    final FileFilter filter = file -> {
        if (file.isDirectory()) return true;
        if (file.exists() && !file.isHidden()) {
            String name = file.getName();
            for (String s : law) {
                if (name.endsWith(s)) return true;
            }
        }
        return false;
    };

    public ChannelFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootFiles = getContext().getExternalFilesDirs(Environment.MEDIA_MOUNTED);

        for (int i = 0; i < rootFiles.length; i++) {//得到存储空间路径
            rootFiles[i] = new File(rootFiles[i].getAbsolutePath().substring(
                    0, rootFiles[i].getAbsolutePath().indexOf("Android")
            ));
        }
        rootPath = new File(Environment.getExternalStorageDirectory().getPath());
        selector = new FileSelector(getContext());
        fileNames = new ArrayList<>();
        handler = new Handler();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_channel, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        choseFileBtn = view.findViewById(R.id.btn_choose_folder);
        fileListView = view.findViewById(R.id.listView_channel);
        lastBtn = view.findViewById(R.id.btn_lase_folder);

        choseFileBtn.setOnClickListener(this);

        selector.setListView(fileListView);
        //selector.setBasePath(rootPath);
        currentFile = rootPath;
        freshView(rootFiles);
        fileListView.setOnItemClickListener(this);
        lastBtn.setOnClickListener(lastBtnView -> {//父类文件按钮
            currentFile = new File(currentFile.getParent());
            freshView(currentFile);
        });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        currentFile = files[position];
        freshView(currentFile);
    }

    private void freshView(File file) {//刷新视图
        if (file.isDirectory()) {
            //fileListView.removeAllViewsInLayout();
            File[] cache = selector.listFile(file, filter);
            if (cache != null) {
                files = cache;
            }
            fileNames.clear();
            for (File f : files) {
                fileNames.add(f.getName());
            }
        } else {
            Toast.makeText(getContext(), file.getName(), Toast.LENGTH_SHORT).show();
        }
        for (File f : rootFiles) {
            lastBtn.setEnabled(!f.equals(currentFile));
        }
    }

    private void freshView(File[] parentFiles) {
        files = selector.listFile(parentFiles);
        fileNames.clear();
        for (File f : files) {
            fileNames.add(f.getName());
        }
        for (File f : rootFiles) {
            lastBtn.setEnabled(!f.equals(currentFile));
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) context;
    }

    @Override
    public void onClick(View v) {//选择文件按钮点击
        bundle = new Bundle();
        if (currentFile.isFile()) {
            Intent intent = new Intent(getContext(), MusicService.class);
            intent.setData(Uri.fromFile(currentFile));
            getContext().bindService(intent, this, Service.BIND_AUTO_CREATE);
            return;
        }

        bundle.putString("file_path", currentFile.getAbsolutePath());
        mainActivity.currentFile = currentFile.getAbsoluteFile();
        mainActivity.getMessage(bundle);
        mainActivity.playerFragment = new PlayerFragment();
        mainActivity.ft = mainActivity.getSupportFragmentManager().beginTransaction();
        mainActivity.ft.replace(R.id.fragment_frame, mainActivity.playerFragment);
        mainActivity.ft.commit();
        mainActivity.changeButton(1);//1。播放器，2，频道
        onStop();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}